package com.example.makerspace.mapper;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.google.gson.Gson;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author River
 * @version 1.0
 * @date 2023/9/27 23:30
 * @description:
 */
public class MybatisMapHandler extends BaseTypeHandler<Map<String,String>> {
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int columnIndex, Map<String, String> stringStringMap, JdbcType jdbcType) throws SQLException {
        // 转化成String存入数据库
        String jsonString = JSON.toJSONString(stringStringMap);
        preparedStatement.setString(columnIndex,  jsonString);
    }


    /**
     * 这个是get方法，可以简单理解成jdbcType转化成javaType
     * 在select的时候触发
     */
    @Override
    public Map<String, String> getNullableResult(ResultSet resultSet, String columnName) throws SQLException {
        Map<String, String> map = new HashMap<String, String>();
        String string = resultSet.getString(columnName);
        Gson gson = new Gson();
        map = gson.fromJson(string, map.getClass());
        return map;
    }


    /**
     * 重载版本
     * 根据下标位置查
     */
    @Override
    public  Map<String, String>  getNullableResult(ResultSet resultSet, int columnIndex) throws SQLException {
        Map<String, String> map = new HashMap<String, String>();
        String string = resultSet.getString(columnIndex);
        Gson gson = new Gson();
        map = gson.fromJson(string, map.getClass());
        return map;
    }

    /**
     * 重载版本
     * 根据下标位置查
     */
    @Override
    public  Map<String, String>  getNullableResult(CallableStatement callableStatement, int columnIndex) throws SQLException {
        Map<String, String> map = new HashMap<String, String>();
        String string = callableStatement.getString(columnIndex);
        Gson gson = new Gson();
        map = gson.fromJson(string, map.getClass());
        return map;
    }
}
